/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  
	
	function formElementDisplayDetails() {}
	formElementDisplayDetails.prototype = {
		dataElementNames : ['icita07', 'icita08','fromformname','order', 'baseuri','id','taborder','legend','label','type','text','sourceText'],
		columnHeaders : ['column.header.icita07.label', 'column.header.icita08.label','column.header.name.label','column.header.order.label','column.header.baseuri.label','column.header.id.label','column.header.taborder.label','column.header.legend.label','column.header.label.label', 'column.header.type.label', 'column.header.currentvalue.label', 'column.header.source.label'],
		
		accessIssuesDataElementNames : ['missinglegend', 'encapsulatinglabel', 'missinglabelandtitle', 'missingaltandtitle', 'missingvalueandtitle', 'missingbuttoncontent', 'duplicatelabel', 'badornostyle', 'nonfocusablesibling', 'emptylable', 'emptylegend', 'emptytitle', 'duplicateID'],
		accessIssuesAttrNames : ['', '', '', '', '', '', '', '', '', '', '', '', 'id'],
		accessIssuesMessages : ['forms.msg.missinglegend', 'forms.msg.encapsulatinglabel', 'forms.msg.missinglabelandtitle', 'forms.msg.missingaltandtitle', 'forms.msg.missingvalueandtitle', 'forms.msg.missingbuttoncontent', 'forms.msg.duplicatelabel', 'forms.msg.badornostyle', 'forms.msg.nonfocusablesibling', 'forms.msg.emptylable', 'forms.msg.emptylegend', 'forms.msg.emptytitle', 'forms.msg.duplicateID'],
		
		accessIssuesUseObjectFunctions : true,
	}
	var formElementDisplayDetails = new formElementDisplayDetails();
	
	function formElementObject(tnode, fromformname) {
		this.node = tnode;
		this.fromformname = fromformname;
		this.parseElement();
	}
	formElementObject.prototype = {
		icita07 : "",
		icita08 : "",
		baseuri : '',
		fromformname: '',
		legend : null,
		labelNode : null,
		label : false,
		id : '',
		node : null,
		name : false,
		tabOrder : -1,
		tagName : "",
		type : "",
		alt : "",
		source: false,
		missinglegend : false,
		encapsulatinglabel : false,
		missinglabelandtitle : false,
		missingaltandtitle : false,
		missingvalueandtitle : false,
		missingbuttoncontent : false,
		duplicatelabel : false,
		badornostyle : false,
		nonfocusablesibling : false,
		emptylable : false,
		emptylegend : false,
		emptytitle : false, 
		duplicateID : false,
		display : true,
		displayDetails: formElementDisplayDetails,
		parseLabelFromButton : function (node) {
	
			var aLabel = "",fromSrc = "";
			for (i = 0; i < node.childNodes.length; i++){
				var myName = node.childNodes[i].nodeName;
				if (node.childNodes[i].nodeName.toLowerCase()== '#text')	{ //3/4/08 SMF Use content first
					if (node.childNodes[i].textContent) { 
						aLabel += cleanSpaces(node.childNodes[i].textContent);
						if (aLabel.length > 0) {fromSrc = AE.source_content; aLabel += ' '}
					}	
				}
				if (node.childNodes[i].nodeName.toLowerCase()== 'img')	{
					aLabel += cleanSpaces(node.childNodes[i].getAttribute('alt'));
					if (aLabel.length > 0) {if (fromSrc == "") {fromSrc = AE.source_alt;} aLabel += ' '}
				}
			}
			if (aLabel != "") {this.label = aLabel; this.source = fromSrc; return true;} else {this.missingbuttoncontent = true; return false;}
	
		},
		labelFromAttribute : function (node, attributeName, labelSrcName){
			if (node.hasAttribute(attributeName)) {
				this.label = cleanSpaces(node.getAttribute(attributeName));
				if (this.label.length > 0) {
					this.source = labelSrcName;
					return true;
				} 
				return false;
			}
			
		},
		parseLabel : function () {
			if (this.tagName == 'input' || this.tagName.indexOf('select') >= 0 || this.tagName == 'textarea' || this.tagName == 'button') {
				if (this.node.hasAttribute('title') && cleanSpaces(this.node.getAttribute('title')).length == 0) { this.emptytitle = true; this.source =AE.source_title;}
			}
			if (this.tagName == 'button') {
				if (this.parseLabelFromButton(this.node)) {	return;	}
			}
			if (this.tagName == 'input' && this.type == 'image') { // input <type=image>
				if (this.emptytitle == true) return;
				if (!this.labelFromAttribute(this.node, 'title', AE.source_title) && !this.labelFromAttribute(this.node, 'alt', AE.source_alt)) this.missingaltandtitle = true;
				return;
			}
			if (this.tagName == 'input' && (this.type == 'submit' || this.type == 'reset' || this.type == 'button')) {
				if (this.emptytitle == true) return;
				if (!this.labelFromAttribute(this.node, 'title', AE.source_title) && !this.labelFromAttribute(this.node, 'value', AE.source_value)) this.missingvalueandtitle = true;
				return;
			}
			
			if (this.node.id) {
				this.id = this.node.id;
				this.labelNode = FindLabelNodeForId(this.node.id,this.node.ownerDocument);
				if (this.labelNode) {
					this.label = getDisplayableTextRecursively(this.labelNode);
					this.source = AE.source_label;
					if (this.label.length  < 1) {this.emptylable = true;}
					return;
				}
			}
			if ((this.tagName.indexOf('select') >= 0 || this.tagName == 'textarea')) {
				if (FindLabelFromParents(this.node)) this.encapsulatinglabel = true;
				if (this.label == false && !this.labelFromAttribute(this.node, 'title', AE.source_title)) this.missinglabelandtitle = true;
				return;
			}
			if (this.tagName == 'input' && this.node.type && (this.type == 'text' || this.type == 'file' || this.type == 'password' || this.type == 'checkbox'|| this.type == 'radio')) { 
				if (this.label == false && !this.labelFromAttribute(this.node, 'title', AE.source_title)) this.missinglabelandtitle = true;
				return;
			}
			return;//Should be unreachable
		},
		parseElement : function() {
			this.baseuri = getBaseURI(this.node);
			if (this.node.hasAttribute("name")) {
				this.name = cleanSpaces(GetValueFromAttributes(this.node,['name'],""));
			}
			this.tabOrder = this.node.tabOrder;
			this.id = accessext_getBundleSingleString('none');
			this.source = AE.source_none;
			this.tagName = this.node.tagName.toLowerCase();
			if (this.node.type) this.type = this.node.type.toLowerCase();
			// Parse the label
			this.parseLabel();
			if (!this.label){					
				this.label = accessext_getBundleSingleString('forms.noLabel');
				if (this.source == '') this.source = AE.source_none;
			}
			
	/* too many false hits
			if (this.tagName.indexOf('select') >= 0 || this.tagName == 'textarea' || this.tagName == 'button' || (this.tagName == 'input' && (this.type == 'text' || this.type == 'password'))) {
				if (this.node.hasAttribute("style")) {	
					var nodestyle = this.node.getAttribute("style"); 				
					var fontSize = nodestyle.toLowerCase();
					if (fontSize.indexOf("font-size") >= 0) {
						fontSize = fontSize.substring(fontSize.indexOf("font-size"));
						if (fontSize.indexOf(";") >= 0) { fontSize = fontSize.substring(0, fontSize.indexOf(";"));}
						if ((fontSize.indexOf('pt') >= 0) || (fontSize.indexOf('px') >= 0)  || (fontSize.indexOf('in') >= 0) || (fontSize.indexOf('cm') >= 0)  || (fontSize.indexOf('mm') >= 0) ) {
							this.badornostyle = true;
						}
					} 
				} else {
					this.badornostyle = true;
				}
			}
	*/
			
			//See if this is part of a fieldset, and if so, get the legend.
			//Todo : rework GetLegendForNode
			var fieldSetNode = getFieldSetNodeForElement(this.node);
			if (fieldSetNode != null) {
				var legend;
				for (legend = 0; legend < fieldSetNode.childNodes.length; legend++) {
					if (fieldSetNode.childNodes[legend].tagName &&
						fieldSetNode.childNodes[legend].tagName.toLowerCase() == 'legend') {
						this.legend = fieldSetNode.childNodes[legend].textContent;
						break;
					}
				}
				if (this.legend == null) {
					this.missinglegend = true;
				} else {
					this.legend = cleanSpaces(this.legend);
					if (this.legend.length  < 1) {this.emptylegend = true; }
				}		
			}
			
			if (this.legend == null) {
				this.legend = accessext_getBundleSingleString('none');
			} 
			
			//Todo: fix this
			this.alt = this.legend;
			
			this.text = this.node.value;
			
			switch (this.type) {
				case "radio":
					if (this.node.checked)
						this.text = accessext_getBundleString('forms.radioChecked',this.text);
				break;
				case "hidden":
					//Don't add hidden fields
					this.display = false;
				break;
				case "button":
				case "submit":
				case "reset":
					this.text = "";
				break;
				case "select-one":
					this.text = accessext_getBundleString((this.node.options.selectedIndex >= 0 ? 
						'forms.selectOne.one' : 'forms.selectOne.none'),
						new Array(this.node.options.length.toString()));
	
				break;
				case "select-multiple":
					//See how many are selected
					var count = 0;
					for (var i = 0; i < this.node.options.length; i ++) {
						if (this.node.options[i].selected) {
							count ++;
						}
					}
					this.text = accessext_getBundleString((count == 1 ?
						'forms.multipleSelect.single' : 'forms.multipleSelect.plural'),
						[count.toString(),this.node.options.length.toString()]);
				break;
			}
			
			if (this.node.disabled) {
				this.label = this.label + " " + accessext_getBundleSingleString('forms.tagLabel.disabled');
			} else if (this.node.readOnly) {
				this.label = this.label + " " + accessext_getBundleSingleString('forms.tagLabel.readOnly');
			}
			
			if (this.name == false) {
				this.name = accessext_getBundleSingleString('forms.noName');
			}
			this.sourceText = this.getSourceText();
		},
		displayOrder : 0,
		sourceText : "",
		getTreeItem : function(doc) {
			this.displayOrder = this.order - 1;
			var item = accesxt_generateTreeboxResults(doc,this);
			item.setAttribute('hidden',false == this.display);
			return item;
		},
		getSourceText : function() {
			switch (this.source) {
				case AE.source_label:
					return accessext_getBundleSingleString("forms.source.label");
				break;
				case AE.source_title:
					return accessext_getBundleSingleString("forms.source.title");
				break;
				case AE.source_value:
					return accessext_getBundleSingleString("forms.source.value");
				break;
				case AE.source_name:
					return accessext_getBundleSingleString("forms.source.name");
				break;
				case AE.source_alt:
					return accessext_getBundleSingleString("forms.source.alt");
				break;
				case AE.source_content:
					return accessext_getBundleSingleString("forms.source.content");
				break;
				case AE.source_default:
					return accessext_getBundleSingleString("forms.source.default");
				break;
				case AE.source_none:
				default : 
					return accessext_getBundleSingleString("forms.source.none");
				break;
			}
			return "";
		},
		setRowColor : function (item) {
			var row = item.getElementsByTagName('treerow');	
			var rowType = '';
			for (var j = 0; j < this.displayDetails.accessIssuesDataElementNames.length; j++) {
				var issue = this.displayDetails.accessIssuesDataElementNames[j];
				if (this[issue] == true) {
					if (rowType != 'failRow') {
						var severity = getErrMsgSeverity(this.displayDetails.accessIssuesMessages[j], currStandard());
						if (rowType != 'warnRow') {
							rowType = severity.toLowerCase() + 'Row';
						}
					}
				}
			}
			if (rowType != '') {
				row[0].setAttribute('properties',rowType);
			}
		},
		getNoteText : function() {
			try {
				var note = '';
				var tmp = '';
				var currStd = currStandard();
				var notApplicable = accessext_getBundleSingleString('msg.unenforced');
				if (this.missinglegend) {
					var severity = getErrMsgSeverity('forms.msg.missinglegend', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.missinglegend') + ' \n'; }
				}
				if (this.encapsulatinglabel) {
					var severity = getErrMsgSeverity('forms.msg.encapsulatinglabel', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.encapsulatinglabel') + ' \n'; }
				}
				if (this.missinglabelandtitle) {
					var severity = getErrMsgSeverity('forms.msg.missinglabelandtitle', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.missinglabelandtitle') + ' \n'; }
				}
				if (this.missingaltandtitle) {
					var severity = getErrMsgSeverity('forms.msg.missingaltandtitle', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.missingaltandtitle') + ' \n'; }
				}
				if (this.missingvalueandtitle) {
					var severity = getErrMsgSeverity('forms.msg.missingvalueandtitle', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.missingvalueandtitle') + ' \n'; }
				}
				if (this.missingbuttoncontent) {
					var severity = getErrMsgSeverity('forms.msg.missingbuttoncontent', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.missingbuttoncontent') + ' \n'; }
				}
				if (this.duplicatelabel) {
					var severity = getErrMsgSeverity('forms.msg.duplicatelabel', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.duplicatelabel') + ' \n'; }
				}
				if (this.badornostyle) {
					var severity = getErrMsgSeverity('forms.msg.badornostyle', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.badornostyle') + ' \n'; }
				}
				if (this.nonfocusablesibling) {
					var severity = getErrMsgSeverity('forms.msg.nonfocusablesibling', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.nonfocusablesibling') + ' \n'; }
				}
				if (this.emptylable) {
					var severity = getErrMsgSeverity('forms.msg.emptylable', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.emptylable') + ' \n'; }
				}
				if (this.emptylegend) {
					var severity = getErrMsgSeverity('forms.msg.emptylegend', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.emptylegend') + ' \n'; }
				}
				if (this.emptytitle) {
					var severity = getErrMsgSeverity('forms.msg.emptytitle', currStd);
					if (severity != notApplicable) {note += severity + ': ' + accessext_getBundleSingleString('forms.msg.emptytitle') + ' \n'; }
				}
				if (this.duplicateID) {
					var severity = getErrMsgSeverity('forms.msg.duplicateID', currStd);
					if (severity != notApplicable) {
						tmp = accessext_getBundleSingleString('forms.msg.duplicateID');
						tmp = tmp.replace('%1', this.id);
						note += severity + ': ' + tmp + ' \n'; 
					}
				}
			} catch (ex) {
				accessext_consoleDump('formElementObject.getNoteText exception: ', ex);
			}
			return note;
		},
	
		highlightAndFocus : function() {
		}
	}
	
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{	
	newFormElementObject: function(tnode, fromformname) { 
		var n = new formElementObject(tnode, fromformname);
		return n; 
	},
	
	getFormElementDisplayDetails: function() {
		return formElementDisplayDetails;
	},
	
	getAllFormElementsNotBelongingToForm: function (doc) {
		//	this can probably all be done in xpath, using ancestor or descendent, not just the basic element selection
		// 11/23/07 SF this does not work sometimes - I think it is when the doc.contenttype = application/xhtml+xml
		var xp = "//button|//input|//textarea|//select";
		var elements = new Array();
		var xpathResult = doc.evaluate(xp, doc, accessext_NSResolver, XPathResult.ANY_TYPE,null);
		var r = xpathResult.iterateNext();
		while (r) {
			if (null == r.form) {
				elements[elements.length] = r;
			}
			r = xpathResult.iterateNext();
		}
		return elements;
	}
});
}});